package com.zwk.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.zwk.common.to.es.SkuEsModel;
import com.zwk.gulimallsearch.config.ESConfig;
import com.zwk.gulimallsearch.constant.EsConstant;
import com.zwk.gulimallsearch.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient esClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest requests=new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest request = new IndexRequest(EsConstant.PRODUCT_INDEX);
            String jsonString = JSON.toJSONString(skuEsModel);
            request.source(jsonString, XContentType.JSON);
            requests.add(request);
        }
        BulkResponse responses = esClient.bulk(requests,ESConfig.COMMON_OPTIONS);
        return !responses.hasFailures();
    }
}
